package com.ysd.util;


import cn.hutool.json.JSONUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ysd.common.Result;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * jwt工具类
 */
@Slf4j
@Data
@Component
@ConfigurationProperties(prefix = "ysd.jwt")
public class JwtUtils {

    // 过期时间 24 小时,此处时间更改的同时需要更改RedisResultManager中的时间。后期优化为数据运行参数
    private static final long EXPIRE_TIME = 7 * 60 * 24 * 60 * 1000;

    // 密钥
    private static final String SECRET = "123ysd!@#";

    /**
     * 生成 token
     */
    public static String createToken(String username,String userId) {
        try {
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            // 附带username信息
            return JWT.create()
                    .withClaim("username", username)
                    .withClaim("userId", userId)
                    //到期时间
                    .withExpiresAt(date)
                    //创建一个新的JWT，并使用给定的算法进行标记
                    .sign(algorithm);
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }

    /**
     * 校验 token 是否正确
     */
    public static boolean verify(String token, String username,String userId) throws UnsupportedEncodingException {
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        //在token中附带了username信息
        JWTVerifier verifier = JWT.require(algorithm).acceptLeeway(2)
                .withClaim("username", username)
                .withClaim("userId", userId)
                .build();
        //验证 token
        verifier.verify(token);
        return true;
    }
    private void responseError(ServletResponse response, String message) throws IOException {
        HttpServletResponse hs =  (HttpServletResponse)response;
        hs.setContentType("application/json;charset=utf8");
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(JSONUtil.toJsonStr(Result.fail(402,"用户token错误，请重新登录",null)).getBytes("UTF-8"));
        outputStream.flush();
        outputStream.close();
    }


    /**
     * 获得token中的信息，无需secret解密也能获得
     */
    public static String getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 获得token中的信息，无需secret解密也能获得
     */
    public static String getUserId(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("userId").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }
}
